package com.ihai.spring.boot.sample.integration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlowBuilder;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.context.IntegrationFlowContext;
import org.springframework.integration.http.dsl.Http;
import org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway;
import org.springframework.integration.http.inbound.RequestMapping;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;


/**
 * DESC
 *
 * @author Adolphus
 * @date 2019/1/30
 */
@SpringBootApplication
public class IntegrationApplication {
    private static ConfigurableApplicationContext context;
    public static void main(String[] args) {
        context = SpringApplication.run(IntegrationApplication.class, args);
        IntegrationFlowContext fc = context.getBean(IntegrationFlowContext.class);
        fc.registration(inbound("test")).id("test-inbound").register();
        fc.registration(outbound("test")).id("test-outbound").register();

        channel.subscribe(new MessageHandler() {

            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                System.out.println(message.getPayload());
            }
            
        });
    }

    private static PublishSubscribeChannel channel = new PublishSubscribeChannel();

    // @Bean
    public static IntegrationFlow inbound(String code) {
        return IntegrationFlows.from(
            Http.inboundGateway("/foo")
                .requestMapping(m -> m.methods(HttpMethod.GET))
                .requestPayloadType(String.class)
                .replyChannel(channel)
        )
        .channel(code+".request.channel")
        .get();
    }

    public static IntegrationFlow outbound(String code) {
        return IntegrationFlows.from(code+".request.channel")
        .handle(
            Http.outboundGateway("http://www.baidu.com")
                .httpMethod(HttpMethod.GET)
                .expectedResponseType(String.class)
        )
        .channel(channel)
        .get();
    }

}
